package cn.ghb.eshop.sys.users.service;

import cn.ghb.eshop.sys.users.entity.User;
import cn.ghb.eshop.sys.users.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author Clown
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    public User getByUsername(String username) {
        Assert.hasText(username, "用户名不能为空");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(User::getUsername, username);
        return getOne(queryWrapper);
    }

    @SneakyThrows
    @Override
    public boolean save(User entity) {
        checkUserExists(entity.getUsername());
        entity.setPassword(entity.getPassword());
        return super.save(entity);
    }

    public void checkUserExists(String username) throws Exception {
        User user = getByUsername(username);
        if (user != null && user.getId() != null) {
            throw new Exception("用户名已存在");
        }
    }

}
